package com.Servlet;

import com.DAO.StudentDao;
import com.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/editStudent")
public class EditStudentServlet extends HttpServlet {
    private StudentDao studentDao;

    @Override
    public void init() throws ServletException {
        studentDao = new StudentDao();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {

        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取学生id
        String studentId = request.getParameter("id");
        if (studentId != null) {
            try {
                // 获取学生信息
                Student student = studentDao.getStudentById(Integer.parseInt(studentId));
                // 将学生信息存入request作用域
                request.setAttribute("student", student);
                // 转发到编辑页面
                request.getRequestDispatcher("/editStudent.jsp").forward(request, response);
            } catch (SQLException e) {
                e.printStackTrace();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误");
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少学号参数");
        }
    }
}
